package com.zetyun.tiger.sql.dkm;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.text.StrFormatter;
import cn.hutool.db.Db;
import cn.hutool.db.Entity;

import java.nio.charset.StandardCharsets;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class GenSrDkmApp {

    public static void main(String[] args) throws SQLException {
        ArrayList<String> list = new ArrayList<>();

        //查询
        List<Entity> result = Db.use()
                .query("select concat('DKM_ODS_',system_name,'_',tb_name) full_name,tb_name from ods_table ot " );

        String kSql = FileUtil.readString(Objects.requireNonNull(
                GenSrDkmApp.class.getResource("/primary_key.sql")), StandardCharsets.UTF_8);
        String fieldSql = FileUtil.readString(Objects.requireNonNull(
                GenSrDkmApp.class.getResource("/field.sql")), StandardCharsets.UTF_8);
        String dkmSqlTemplate = FileUtil.readString(Objects.requireNonNull(
                GenSrDkmApp.class.getResource("/dkm.template")), StandardCharsets.UTF_8);

        for (Entity entity : result) {
            String tb_name = entity.getStr("tb_name");
            List<Entity> key = Db.use().query(StrFormatter.format(kSql, tb_name));
            String all_key = key.get(0).getStr("all_key");

            List<Entity> query = Db.use().query(StrFormatter.format(fieldSql,
                    entity.getStr("tb_name"),
                    entity.getStr("tb_name")));

            StringBuilder sb = new StringBuilder();
            String tb_cn_name = "";
            for (Entity e : query) {
                tb_cn_name = e.getStr("tb_cn_name");
                String field_def = e.getStr("field_def")
                        .replace("DECIMAL(22)","DECIMAL(22, 0)")
                        .replace("SMALLINT(2)","SMALLINT")
                        .replace("CLOB","STRING")
                        .replace("LONGTEXT", "STRING");

                sb.append(field_def).append("\n");
            }

            String sql = StrFormatter.format(
                    dkmSqlTemplate,
                    tb_cn_name,
                    entity.getStr("full_name"),
                    entity.getStr("full_name"),
                    sb,
                    all_key,
                    tb_cn_name,
                    all_key
            );
            list.add(sql);

//            System.out.println(sql);
//            return;
        }

        FileUtil.writeLines(list,"sr-dkm.sql",StandardCharsets.UTF_8);

    }
}
